package github.sf.mod.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Loads {
    Logger logger = Logger.getLogger(this.getClass().getName());

    public InputStream load(String fileName) {
        //直接去查找fileName的位置
        InputStream inputStream = loadFromPrimitivePath(fileName);
        if (inputStream == null) {
            //从工作目录找
            inputStream = loadFileFromWorkDir(fileName);
            if (inputStream == null) {
                inputStream = loadFileFromJar(fileName);
                return inputStream;
            }
        }
        return inputStream;
    }

    private InputStream loadFromPrimitivePath(String fileName) {
        return loadStream(fileName);
    }

    private InputStream loadFileFromWorkDir(String fileName) {
        String path = "";
        try {
            URL resource = Loads.class.getResource("/");
            path = resource.getPath();
        } catch (Exception e) {
            return null;
        }

        String realFileName = path + fileName;
        return loadStream(realFileName);
    }

    private InputStream loadFileFromJar(String fileName) {
        return Loads.class.getResourceAsStream(fileName);
    }

    public InputStream loadStream(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        } else {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                return fis;
            } catch (FileNotFoundException ex) {
                logger.log(Level.OFF, "文件未找到", ex.getMessage());
                return null;
            }
        }
    }

}
